﻿/*
Copyright (c) 2008 Jonathan Johnson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;

namespace SocksV4Proxy
{
    public class Socks4ProxyException : Exception
    {
        public Socks4ProxyException(String messageFormat, Exception innerException, params Object[] args)
            : base(String.Format(messageFormat, args), innerException) { }
        public Socks4ProxyException(String messageFormat, params Object[] args)
            : this(messageFormat, null, args) { }
    }

    public class Socks4Proxy
    {
        public static Socket ConnectViaSocks4Proxy(String proxyAddress, Int16 proxyPort, String remoteAddress, Int16 remotePort)
        {
            try
            {

                IPAddress[] addresses = (from addr in Dns.GetHostAddresses(remoteAddress)
                                         where addr.GetAddressBytes().Length == 4
                                         select addr).ToArray();
                if (addresses.Length == 0) return null;

                Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                s.Connect(proxyAddress, (Int32)proxyPort);
                List<byte> socksProtocol = new List<byte>();
                // Socks protocol version
                socksProtocol.Add(0x04);
                // Request type. 1 = remote tcp connection
                socksProtocol.Add(0x01);
                // Remote port, Int16, network byte order
                socksProtocol.Add((byte)(remotePort >> 8 & 0xFF));
                socksProtocol.Add((byte)(remotePort & 0xFF));
                // Remote address, network byte order
                socksProtocol.AddRange(addresses[0].GetAddressBytes());
                // Username -- not needed, null terminated
                socksProtocol.Add(0x00);
                s.Send(socksProtocol.ToArray(), SocketFlags.None);
                byte[] buffer = new byte[512];
                int ct = s.Receive(buffer, 8, SocketFlags.None);
                // For some odd reason, they use 0x5a as a success indicator... and on the second byte at that!
                // The first byte is supposed to be null, and then the rest are arbitrary bytes.
                if (buffer[1] == 0x5a)
                {
                    return s;
                }
            }
            catch (Exception ex)
            {
                throw new Socks4ProxyException("An error occurred connecting to the proxy.", ex);
            }

            return null;
        }
    }
}
